package py.una.pol.tesis.ii.emergenciasmovil.app.fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Scroller;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import py.una.pol.tesis.ii.emergenciasmovil.app.R;
import py.una.pol.tesis.ii.emergenciasmovil.app.dto.Respuesta;
import py.una.pol.tesis.ii.emergenciasmovil.app.util.UtilParse;


public class NuevaMedicionFragment extends Fragment implements AdapterView.OnItemSelectedListener {
    private static final String TAG = "NuevaMedicionFragment";
    private FragmentActivity myContext;

    String[] values =
            {"Presión Alta", "Diabetes"};
    Spinner spinnerDiagnosticos;
    EditText editTextParam1, editTextParam2;
    private RequestQueue requestQueue;
    private JsonObjectRequest jsArrayRequest;
    // Progress dialog
    private ProgressDialog pDialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_nueva_medicion, container, false);

        spinnerDiagnosticos = (Spinner) v.findViewById(R.id.spinner_diagnosticos);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(),
                R.layout.spinner_diagnosticos_item, values);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinnerDiagnosticos.setAdapter(adapter);

        spinnerDiagnosticos.setOnItemSelectedListener(this);

        editTextParam1 = (EditText) v.findViewById(R.id.editTextParam1);
        editTextParam1.setScroller(new Scroller(this.getActivity()));
        editTextParam1.setMaxLines(2);
        editTextParam1.setVerticalScrollBarEnabled(true);
        editTextParam1.setMovementMethod(new ScrollingMovementMethod());

        editTextParam2 = (EditText) v.findViewById(R.id.editTextParam2);
        editTextParam2.setScroller(new Scroller(this.getActivity()));
        editTextParam2.setMaxLines(2);
        editTextParam2.setVerticalScrollBarEnabled(true);
        editTextParam2.setMovementMethod(new ScrollingMovementMethod());

        Button buttonEnviar = (Button) v.findViewById(R.id.buttonEnviar);
        buttonEnviar.setOnClickListener(new BotonEnviarClickListener());

        return v;
    }

    public void onItemSelected(AdapterView<?> parent, View view,
                               int pos, long id) {
        if (pos == 0) {
            editTextParam1.setHint("presión sistólica");
            editTextParam2.setVisibility(View.VISIBLE);
            editTextParam2.setHint("presión diastólica");

        } else {
            editTextParam1.setHint("glucosa");
            editTextParam2.setVisibility(View.INVISIBLE);
        }

        Toast.makeText(NuevaMedicionFragment.this.getActivity(),
                "Diagnóstico Seleccionado: " + values[pos],
                Toast.LENGTH_LONG).show();
    }

    public void onNothingSelected(AdapterView<?> parent) {
        // Another interface callback
    }

    @Override
    public void onAttach(Activity activity) {
        myContext = (FragmentActivity) activity;
        super.onAttach(activity);
    }

    private class BotonEnviarClickListener implements
            View.OnClickListener {

        public void onClick(View v) {
            if (spinnerDiagnosticos.getSelectedItemPosition() == 0) {
                if (editTextParam1.getText().toString().trim().length() == 0 || editTextParam2.getText().toString().trim().length() == 0) {
                    Toast.makeText(getActivity(), "Complete todos los datos.", Toast.LENGTH_SHORT).show();
                    return;
                }
            } else {
                if (editTextParam1.getText().toString().trim().length() == 0) {
                    Toast.makeText(getActivity(), "Complete todos los datos.", Toast.LENGTH_SHORT).show();
                    return;
                }

            }

            try {
                pDialog = new ProgressDialog(NuevaMedicionFragment.this.getActivity());
                pDialog.setMessage("Por favor aguarde...");
                pDialog.setCancelable(false);

                showpDialog();
                requestQueue = Volley.newRequestQueue(getActivity());

                JSONObject jsonAdd = new JSONObject();
                if (spinnerDiagnosticos.getSelectedItemPosition() == 0) {
                    jsonAdd.put("idDiagnostico", "0");
                    jsonAdd.put("parametro1", editTextParam1.getText().toString());
                    jsonAdd.put("parametro2", editTextParam2.getText().toString());
                } else {
                    jsonAdd.put("idDiagnostico", "1");
                    jsonAdd.put("parametro1", editTextParam1.getText().toString());
                }


                jsArrayRequest = new JsonObjectRequest(Request.Method.POST,
                        getActivity().getString(R.string.url_base) + getActivity().getString(R.string.post_agregar_medicion),
                        jsonAdd,
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                hidepDialog();
                                Respuesta resp = UtilParse.parseJson(response);

                                Toast.makeText(getActivity(), resp.getMensaje(), Toast.LENGTH_LONG).show();

                            }

                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Toast.makeText(getActivity(), R.string.error_servidor, Toast.LENGTH_LONG).show();
                                Log.d(TAG, "Error Respuesta en JSON: " + error.getMessage());
                                hidepDialog();
                            }
                        }
                );

                requestQueue.add(jsArrayRequest);
                //finish();
            } catch (JSONException ex) {
                ex.printStackTrace();
            }

        }
    }

    private void showpDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hidepDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}
